﻿using Microsoft.AspNetCore.Mvc;
using MongoDb.Api.Models;
using MongoDb.Api.Services;
using MongoDB.Bson;

namespace MongoDb.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProductController : ControllerBase
    {
        private readonly ILogger<ProductController> _logger;
        private readonly IProductService _productService;

        public ProductController(ILogger<ProductController> logger, IProductService productService)
        {
            _logger = logger;
            _productService = productService;
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<Product> CreateProduct(Product product)
        {
            // 直接创建一个新的ObjectId
            ObjectId objectId = ObjectId.GenerateNewId();
            product.Id = objectId.ToString();
            _productService.Create(product);
            return CreatedAtAction("GetProduct", new { id = product.Id }, product);
        }

        [HttpGet("{id}")]
        public ActionResult<Product> GetProduct(string id)
        {
            var product = _productService.GetProductById(id);

            if (product == null)
            {
                return NotFound();
            }
            return product;
        }


    }
}
